﻿using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.Domain.ProductionWorking;
using MangoMes.Commont.Domain.Products;
using MangoMes.Commont.Domain.Purchase;
using MangoMes.Commont.Domain.SellStocks;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MangoMes.Write.API.Applications.ProductionWorkOrders;
using MediatR;
using MySql.Data.MySqlClient;

namespace MangoMes.Write.API.Applications.PurchaseStorags
{
    public class ExecuteHandler : IRequestHandler<ExecuteCommand, ResultsDTO>
    {
        private readonly IBateRepository <PurchaseStorage> purchase;
        private readonly IBateRepository<ProductManage> manage;
        private readonly IBateRepository <Material> material;
        private readonly IBateRepository<Stockremoval> stock;
        private readonly ILogger<ExecuteHandler> logger;

        public ExecuteHandler(IBateRepository<PurchaseStorage> purchase, IBateRepository<ProductManage> manage, IBateRepository<Material> material, IBateRepository<Stockremoval> stock, ILogger<ExecuteHandler> logger)
        {
            this.purchase = purchase;
            this.manage = manage;
            this.material = material;
            this.stock = stock;
            this.logger = logger;
        }
        /// <summary>
        /// 执行入库
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultsDTO> Handle(ExecuteCommand request, CancellationToken cancellationToken)
        {
            DapperHelper dapperHelper = new DapperHelper();
            Stockremoval moval=new Stockremoval();
            ResultsDTO res = new ResultsDTO { Code = 0 };
            string dapper = dapperHelper.MangoMesWrite;
            using (MySqlConnection  conn = new MySqlConnection(dapperHelper.RBACWrite))
            {
                conn.Open();
                using (MySqlTransaction tran = conn.BeginTransaction())
                {
                    try
                    {
                        ProductManage proman = new ProductManage();
                        PurchaseStorage purch=new PurchaseStorage();
                        ProductsSale pro=new ProductsSale();
                        Material mate=new Material();
                        string sql1 = $"SELECT * FROM purchasestorage a JOIN material b on a.PurchaseNo=b.PurchaseNo WHERE a.PurchaseNo='{request.PurchaseNo}' and a.ReceiptState='草稿'";
                        var list= material.GetAll(sql1, mate, dapper).ToList();
                        foreach (var item in list)
                        {
                            string sqlNo = $"select * from productmanage where ProductManageId={item.ProductManageId}";
                            var manageinfo= manage.GetAll(sqlNo, proman, dapper).FirstOrDefault();

                            string sql2 = $"SELECT * FROM stockremoval where ProductManageNode='{manageinfo.ProductManageNode}' and WarehouseId={item.StashId}";
                            var stockinfo = stock.GetAll(sql2, moval, dapper).FirstOrDefault();
                            if (stockinfo != null)
                            {
                                stockinfo.StickWorkNum += item.Num;
                                string sql3 = $"UPDATE stockremoval SET StickWorkNum={stockinfo.StickWorkNum} WHERE StockWorkId={stockinfo.StockWorkId}";
                                res.Code+=await stock.Add(sql3, stockinfo, dapper);
                            }
                            else
                            {
                                moval.StockWorkId = 0;
                                moval.productManageNode = manageinfo.ProductManageNode;
                                moval.productManageName = manageinfo.ProductManageName;
                                moval.WarehouseId = item.StashId;
                                moval.StickWorkNum=item.Num;
                                moval.StockWorkTime = DateTime.Now;
                                string sql4 = $"INSERT INTO stockremoval values(@StockWorkId,@ProductManageNode,@ProductManageName,@StickWorkNum,@StockWorkTime,@WarehouseId)";
                                res.Code+=await stock.Add(sql4, moval, dapper);
                            }
                        }
                        string sql5 = $"UPDATE purchasestorage SET ReceiptState='已完成' WHERE PurchaseNo='{request.PurchaseNo}'";
                        res.Code+=await purchase.Add(sql5, purch, dapper);
                        logger.LogInformation("成功");
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        res.Code = -1;
                        res.Message = ex.Message;
                        logger.LogError("失败"+ex.Message);
                    }
                    return res;
                }
            }
        }
    }
}
